package com.sunrise.gateway.web.core;

import com.dap.cache.common.RedisComponentInterface;
import com.dap.param.StringInput;
import com.sunrise.gateway.FrontendVersionManagerBase;
import com.sunrise.gateway.commons.CommonUtils;
import com.sunrise.gateway.commons.SessionRequestExtraAuthUtil;
import com.sunrise.gateway.commons.UriFilterUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/****
 * 请求转发核心功能
 * @author wangmin
 */
@Service
public class ExchangeEngine extends EngineBase {
    @Autowired
    private RedisComponentInterface redisComponentInterface;
    @Value("${lastRequest.expire.milliseconds}")
    private long lastRequestExpireMilliseconds;
    @Value("${app.env}")
    private String appEnv;

    public String execute(HttpServletRequest req, HttpServletResponse resp) {
        String group = CommonUtils.getGroup(req);
        StringInput stringInput = CommonUtils.parseRequestStringInput(req);

        fillAndValidate(req, group, stringInput);

        return executeRequestStr(group, stringInput, true);
    }

    protected void fillAndValidate(HttpServletRequest req, String group, StringInput stringInput) {
        // 前端版本更新, 请求无效
        FrontendVersionManagerBase.checkFrontendVersion(req, stringInput);

        // ctrlData添加基本信息
        fillSessionInfoIntoCtrlDataInterface.fill(stringInput, group, req);

        // 附加验证
        SessionRequestExtraAuthUtil.check(stringInput, redisComponentInterface);

        // 过滤频繁的重复请求
        UriFilterUtils.filterFrequentlyRepeatRequest(
                group, stringInput, redisComponentInterface, lastRequestExpireMilliseconds, appEnv);
    }
}
